package volatiledemo;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/12 14:59
 */

//多线程中出现死循环
/*原因：变量private boolean isRunning存在于公共堆栈和线程的私有堆栈中，
       线程运行时一直从自己的私有堆栈中取得，一直为true
       而runThread.setRunning(false);虽然执行，改变的是公共堆栈中的值，运行的runThread并不知道
 */
public class VolatileDemo1 {

    public static void main(String[] args) throws InterruptedException {
        RunThread runThread = new RunThread();
        runThread.start();
        Thread.sleep(1000);
        runThread.setRunning(false);
        System.out.println("已经赋值为false了");
    }

}

class RunThread extends Thread{

    private volatile boolean isRunning = true;

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean running) {
        isRunning = running;
    }

    @Override
    public void run() {
        System.out.println("进入run了");
        while (isRunning == true){
        }
        System.out.println("线程被停止了");
    }
}
